package DBLayer;
import ModelLayer.*;

import java.sql.*;
import java.util.ArrayList;

public class DBCustomer{
	private Connection con;
	public DBCustomer() {
	      con = DbConnection1.getInstance().getDBcon();
	}
	
	// get all customers
	public ArrayList<Customer> getAllCustomers(boolean retriveAssociation)
    {
        return miscWhere("", retriveAssociation);
    }
	
	// find a customer with a customer id
	public Customer findCustomerId(String customerId, boolean retriveAssociation){
		String wClause = "customerId= '" + customerId + "'";
		return singleWhere(wClause, retriveAssociation);
	}
	
	// search for a customer with a specific name
	public Customer findCustomerName(String customerName, boolean retriveAssociation){
		String wClause = "name is '%" + customerName + "%'";
		System.out.println("searchCustomer " + wClause);
		return singleWhere(customerName, retriveAssociation);
	}
	
	// insert a customer into the table
    public int insertCustomer(Customer customer) throws Exception
    {  //call to get the next customerid number
        int nextID = GetMax.getMaxId("Select max(customerId) from customer");
        nextID = nextID + 1;
        System.out.println("next id = " +  nextID);
  
        int rc = -1;
	    String query="INSERT INTO customer(customerId, name, address, zipcode, city, phoneNo, type)  VALUES('"+
	  		nextID  + "','"  +
		    customer.getName()  + "','"  +
            customer.getAddress() + "','" +
		    customer.getZipCode()  + "','" +
            customer.getCity()  + "','" +
		    customer.getPhoneNo()  + "','" +
            customer.getType()  + "')";
                     
        System.out.println("insert : " + query);
        try{ // insert new customer +  dependent
           Statement stmt = con.createStatement();
           stmt.setQueryTimeout(5);
     	   rc = stmt.executeUpdate(query);
           stmt.close();
      }//end try
       catch(SQLException ex){
          System.out.println("Customer not created");
          throw new Exception ("Customer is not inserted correct");
       }
       return(rc);
    }
    
    // update the data for a customer by customer id
	public int updateCustomer(Customer customer)
	{
		Customer customerObj  = customer;
		int rc=-1;

		String query="UPDATE customer SET "+
		 	  "name = '"+ customerObj.getName() + "', " +
              "address = '"+ customerObj.getAddress() + "', " +
              "zipcode = '"+ customerObj.getZipCode() + "', " +
		      "city = '"+ customerObj.getCity() + "', " +
              "phoneNo = '"+ customerObj.getPhoneNo() + "', " +
		      "type = '"+ customerObj.getType() + "', " +
              " WHERE customerId = '"+ customerObj.getCustomerId() + "'";
                System.out.println("Update query:" + query);
  		try{ // update customer
	 		Statement stmt = con.createStatement();
	 		stmt.setQueryTimeout(5);
	 	 	rc = stmt.executeUpdate(query);

	 	 	stmt.close();
		}//slut try
	 	catch(Exception ex){
	 	 	System.out.println("Update exception in customer db: "+ex);
	  	}
		return(rc);
	}
	
	
	// delete a customer by customer id
	public int delete(String customerId)
	{
        int rc=-1;
	  
	  	String query="DELETE FROM employee WHERE customerId = '" +
				customerId + "'";
                System.out.println(query);
	  	try{ // delete from employee
	 		Statement stmt = con.createStatement();
	 		stmt.setQueryTimeout(5);
	 	  	rc = stmt.executeUpdate(query);
	 	  	stmt.close();
  		}//slut try	
   	        catch(Exception ex){
	 	  	System.out.println("Delete exception in customer db: "+ex);
   	        }
		return(rc);
	}
	
	private ArrayList<Customer> miscWhere(String wClause, boolean retrieveAssociation)
	{
        ResultSet results;
	    ArrayList<Customer> list = new ArrayList<Customer>();	
		
	    String query =  buildQuery(wClause);
  
        try{ // read the invoice from the database
        	Statement stmt = con.createStatement();
        	stmt.setQueryTimeout(5);
        	results = stmt.executeQuery(query);
	 	
	
			while( results.next() ){
				Customer custObj = new Customer();
		     	custObj = buildCustomer(results);	
		     	list.add(custObj);	
			}//end while
			
			stmt.close();  
			
			/*if(retrieveAssociation)
		    {   //The supervisor and department is to be build as well
				for(Employee empObj : list){
		            String superssn = empObj.getSupervisor().getSsn();
		            Employee superEmp = singleWhere(" ssn = '" + superssn + "'",false);
		            empObj.setSupervisor(superEmp);
		            System.out.println("Supervisor is selected");
		           // here the department has to be selected as well
		        }
		    }*/   
				
		}//end try	
	 	catch(Exception e){
	 		System.out.println("Query exception - select: "+e);
			e.printStackTrace();
	 	}
        
		return list;
	}
    
    private Customer singleWhere(String wClause, boolean retrieveAssociation)
	{
		ResultSet results;
		Customer custObj = new Customer();
                
        String query =  buildQuery(wClause);
        System.out.println(query);
        
		try{ // read the employee from the database
	 		Statement stmt = con.createStatement();
	 		stmt.setQueryTimeout(5);
	 		results = stmt.executeQuery(query);
	 		
	 		if( results.next() ){
	 			custObj = buildCustomer(results);
                //association is to be build
                stmt.close();
                
                /*if(retrieveAssociation)
                {   
                    DBSalesOrder dbsalesObj = new DBSalesOrder();
                    custObj.setSalesOrderList(dbsalesObj.findCostumerSalesOrder(custObj.getCustomerId(), false));                   
                }*/
			}
            else{ //no invoice was found
            	custObj = null;
            }
		}//end try	
	 	catch(Exception e){
	 		System.out.println("Query exception: "+e);
	 	}
		return custObj;
	}
	// method for query methods
	private String buildQuery(String wClause)
	{
	    String query="SELECT customerId, name, address, zipcode, city, phoneNo, type FROM customer";		
		if (wClause.length()>0)
			query=query+" WHERE "+ wClause;
			
		return query;
	}
	
	// create a customer for the table
	private Customer buildCustomer(ResultSet results){
		Customer customerObj = new Customer();
        try{ // the columns from the table costumer are used
              customerObj.setCustomerId(results.getString("customerId"));
              customerObj.setName(results.getString("name"));
              customerObj.setAddress(results.getString("address"));
              customerObj.setZipCode(results.getInt("zipcode"));
              customerObj.setCity(results.getString("city"));
              customerObj.setPhoneNo(results.getString("phoneNo"));
              customerObj.setType(results.getInt("type"));
       }
       catch(Exception e)
       {
           System.out.println("Error in building the customer object");
       }
       return customerObj;
    }
}
